const {
	config
} = require('../../common/config.js')
const ServerError = require('../../common/error')
const jwt = require('jwt-simple')

const md5 = require('js-md5')

const db = uniCloud.database();

async function list(page = 0, limit = 10) {
	page = parseInt(page)
	limit = parseInt(limit)
	let {
		affectedDocs,
		data
	} = await db.collection('admin-user').field({
		_id: true,
		username: true,
		avatarUrl: true,
		tel: true,
		menus: true,
		roles: true,
		logintime: true
	}).get();
	return {
		errCode: 0,
		data: data,
		errMsg: "管理员用户列表"
	}
}
async function adminadd() {
	let curtime = Date.now()
	let httpInfo = this.getHttpInfo()
	let {
		username,
		password,
		roles,
		menus,
		avatarUrl,
		tel
	} = JSON.parse(httpInfo.body)
	let md5Pwd = md5(config.secret + password)
	let data = await db.collection("admin-user").add({
		username,
		password: md5Pwd,
		roles,
		menus,
		ctime: curtime,
		avatarUrl,
		token: "",
		logintime: null,
		tel
	})
	if (data.id) {
		return {
			errCode: 0,
			data: data,
			errMsg: "添加成功"
		}
	} else {
		return {
			errCode: 100,
			data: data,
			errMsg: "添加失败"
		}
	}


}
async function adminupdate() {
	let curtime = Date.now()
	let httpInfo = this.getHttpInfo()
	let {
		_id,
		username,
		password,
		roles,
		menus,
		avatarUrl,
		tel
	} = JSON.parse(httpInfo.body)
	let params = {
		username,
		roles,
		menus,
		avatarUrl,
		tel
	};
	if (password) {
		params.md5Pwd = md5(config.secret + password)
	}
	if(!avatarUrl){
		delete params.avatarUrl
	}
	let {
		affectedDocs,
		data
	} = await db.collection('admin-user').doc(_id).update(params);

	return {
		errCode: 0,
		data: data,
		errMsg: "管理员用户列表"
	}
}

async function deleteItem() {
	let httpInfo = this.getHttpInfo()
	let {
		_id
	} = JSON.parse(httpInfo.body)
	if (_id == "641ea6fb28064a03b73b3adf") {
		throw new ServerError("禁止删除超级管理账号", 3010)
	}

	let {
		deleted
	} = await db.collection("admin-user").doc(_id).remove()
	if (deleted) {
		return {
			errCode: 0,
			data: {
				deleted
			},
			errMsg: "删除成功"
		}
	} else {
		throw new ServerError("没有可删除的数据", 3009)
	}

}

async function reset() {
	let md5Pwd = md5(config.secret + "baigui")
	let {
		updated
	} = await db.collection("admin-user").doc("641ea6fb28064a03b73b3adf").update({
		username: "admin",
		password: md5Pwd
	})
	if (updated > 0) {
		return {
			errCode: 0,
			errMsg: "账户重置成功"
		}
	} else {
		return {
			errCode: 204,
			errMsg: "账户重置失败"
		}
	}
}
module.exports = {
	adminlist: list, // 账户列表
	adminreset: reset, //账户重置
	admindelete: deleteItem,
	adminadd: adminadd, // 添加数据
	adminupdate: adminupdate,
	resetsuper: reset
}
